package com.heima.comment.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.heima.comment.dto.*;
import com.heima.comment.entity.*;
import com.heima.comment.feign.UserClient;
import com.heima.comment.service.ICommentRepayService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发表回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        // 判断内容是否大于140字
        if (dto == null || StringUtils.isEmpty(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断是否登录
        System.out.println("2");
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 安全过滤  集成阿里云进行审核  todo
        //保存回复记录
        ApCommentRepay repay =new ApCommentRepay();
        repay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> responseResult = userClient.getUserById(user.getUserId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = responseResult.getData();
            repay.setAuthorName(apUser.getName());
        }
        repay.setCommentId(dto.getCommentId());
        repay.setContent(dto.getContent());
        repay.setLikes(0);
        repay.setCreatedTime(new Date());
        mongoTemplate.save(repay);
        //更新评论的回复数量+1
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(dto.getCommentId()));

        Update update = new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(query,update, ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 回复点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        // 根据回复id来进行点赞
        ApCommentRepayLike commentLike = new ApCommentRepayLike();
        commentLike.setCommentRepayId(dto.getCommentRepayId());
        commentLike.setOperation(dto.getOperation());
        // 判断是否登录
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        commentLike.setAuthorId(user.getUserId());
        // 操作分为点赞和取消点赞
        // 如果是点赞,需要将点赞记录保存到 点赞记录表中
        // 判断当前用户针对当前评论是否已经有点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        // 定义修改的增量
        int count = 0;
        if (one == null) {
            // 没有点赞记录,新增
            if (dto.getOperation() == 0) {
                mongoTemplate.save(commentLike);
                count = 1;
            }
        } else {
            // 如果数据库的状态和当前操作状态一致,不用处理
            // 不一致的话,修改状态,重新保存
            if (dto.getOperation() != one.getOperation()) {
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                if (dto.getOperation() == 0) {
                    count = 1;
                } else {
                    count = -1;
                }
            }
        }
        // 需要将回复中的点赞量做修改
        if (count != 0) {
            Query queryComment = new Query();
            queryComment.addCriteria(Criteria.where("id").is(dto.getCommentRepayId()));
            Update update = new Update();
            // 指定递增的字段和数量
            update.inc("likes", count);
            mongoTemplate.updateFirst(queryComment, update, ApCommentRepay.class);
        }
        return ResponseResult.okResult();

    }

    /***
     * 加载回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {
        // 根据评论id查询回复列表
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        // 根据最小时间查询
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        // 分页查询 指定当前页(从0开始)  每页条数  排序方向  排序字段
        Pageable page = PageRequest.of(0, 10, Sort.Direction.DESC, "createdTime");
        query.with(page);
        List<ApCommentRepay> apComments = mongoTemplate.find(query, ApCommentRepay.class);

        // 给前端返回一个VO对象 ApCommentVo   0：点赞  1：取消点赞
        List<ApCommentRepayVo> vos = new ArrayList<>();
        for (ApCommentRepay apComment : apComments) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apComment, vo);
            // 没有点赞
            vo.setOperation(1);
            vos.add(vo);
        }
        // 判断当前用户是否已经登录
        User user = AppThreadLocalUtil.get();
        // 如果没有登录,不用做其他处理
        if (user == null) {
            return ResponseResult.okResult(vos);
        }
        // 如果有登录,需要判断当前登录用户在查询到的回复列表中是否已经有点赞记录,如果有点赞记录,需要进行高亮显示
        Query likeQuery = new Query();
        likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        // 提取所有的评论id
        List<String> ids = new ArrayList<>();
        for (ApCommentRepay apComment : apComments) {
            ids.add(apComment.getId());
        }
        likeQuery.addCriteria(Criteria.where("commentRepayId").in(ids));
        List<ApCommentRepayLike> apCommentLikes = mongoTemplate.find(likeQuery, ApCommentRepayLike.class);
        // 定义评论id的集合
        List<String> likeIds = new ArrayList<>();
        for (ApCommentRepayLike apCommentLike : apCommentLikes) {
            if(apCommentLike.getOperation()==0){
                likeIds.add(apCommentLike.getCommentRepayId());
            }
        }
        // 遍历结果列表
        for (ApCommentRepayVo vo : vos) {
            if(likeIds.contains(vo.getId())){
                vo.setOperation(0);
            }
        }
        return ResponseResult.okResult(vos);
    }
}
